<template>
  <page-header-wrapper :title="false" >
    <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
      <a-form @submit="handleAdd" :form="form">
        <a-form-item
          label="调整的金额"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
          <a-input
            v-decorator="[ 'chgAmount',{ rules: [{ required: true, message: '请输入金额' }] }]"
            addonAfter="元"
            name="chgAmount"
            placeholder="请输入调整的金额" />
        </a-form-item>
        <a-form-item
          label="串码"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
          <a-textarea
            rows="8"
            placeholder="可添加多个,每行一个串码，错误的串码会被过滤掉"
            name="phoneCodeList"
            v-decorator="[
              'phoneCodeList',{ rules: [{ required: true, message: '请输入串码' }] }
            ]" />
          
        </a-form-item>
        <a-form-item
          :wrapperCol="{ span: 24 }"
          style="text-align: center"
        >
          <a-button htmlType="submit" type="primary" icon="check">添加</a-button>
          <!-- <a-button style="margin-left: 8px">{{ $t('form.basic-form.form.save') }}</a-button> -->
        </a-form-item>
      </a-form>
    </a-card>
    <a-card :body-style="{padding: '24px 32px'}" title="调价商品清单">
      <a-table
        ref="table"
        size="default"
        rowKey="key"
        :columns="columns"
        :data-source="loadData"
      >
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#D15B47" @click="handleDel(record)">删除</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
      <a-form @submit="handleSubmit" :form="form1">
        <a-form-item
          label="调价日期"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
          <a-date-picker
            v-decorator="['orderDate', { initialValue:this.toDays, rules: [{ required: true, message: '请选择' }]}]" 
            style="width:100%" />
        </a-form-item>
        <a-form-item
          label="调价店面"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
          <a-select placeholder="请选择" v-decorator="['storeId',{ rules: [{ required: true, message: '请选择' }] }]">
            <a-select-option :value="i.value" v-for="i in option" :key="i.value">{{ i.label }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="备注"
          :labelCol="{lg: {span: 7}, sm: {span: 7}}"
          :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
          <a-input v-decorator="['memo', {initialValue:''}]" name="memo" placeholder="请输入备注"/>
        </a-form-item>
        <a-form-item
          :wrapperCol="{ span: 24 }"
          style="text-align: center"
        >
          <a-button htmlType="submit" type="primary" icon="check">提交调价</a-button>
          <!-- <a-button style="margin-left: 8px">{{ $t('form.basic-form.form.save') }}</a-button> -->
        </a-form-item>
      </a-form>
    </a-card>
  </page-header-wrapper>
</template>
    
  <script>
  import { getPageBySingleCodeUsingGET,addChgPriceUsingPOST } from '@/api/api/kucunguanli.ts'
  import { getStoreListUsingPOST } from '@/api/api/mendianguanli.ts'
  import moment from 'moment'
    export default {
      name: 'ChangePrice',
      data () {
        return {
          radioStyle:{
            display: 'block',
            height: '30px',
            lineHeight: '30px',
          },
          toDays: moment().format('YYYY-MM-DD'),
          form: this.$form.createForm(this),
          form1: this.$form.createForm(this),
          columns: [
          {
            title: '商品',
            dataIndex: 'goodName'
          },
          {
            title: '原成本(元)',
            dataIndex: 'commCost'
          },
          {
            title: '调整金额(元)',
            dataIndex: 'chgAmount'
          },
          {
          title: '操作',
          dataIndex: 'action',
          width: '220px',
          scopedSlots: { customRender: 'action' }
        }
        ],
        option:[],
        optionParam: {
        pageNo:1,
        pageSize:999,
        queryCondition:'',
        status:1
      },
        // 加载数据方法 必须为 Promise 对象
        loadData:[],
        }
      },
      mounted(){
        this.getOption()
      },
      methods: {
        getOption () {
          getStoreListUsingPOST(this.optionParam).then((res) => {
              this.option = res.data.list.map((item)=>{
                return {
                  label:item.storeName,
                  value:item.id
                }
              })
            })
            .catch((error) => {
              this.confirmLoading = false
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        },
        removeTrim(array){
          for (let i = 0; i < array.length; i++) {
            if (array[i] == '') {
                array.splice(i, 1)
                i = i - 1
              }
            }
          return array
        },
        handleAdd (e) {
            e.preventDefault()
            this.form.validateFields((err, values) => {
              if (!err) {
                getPageBySingleCodeUsingGET({phoneCodeList:this.removeTrim(values.phoneCodeList.split('\n')).toString()}).then((res) => {
                  const data = res.data.list.map((item, index) => {
                  return {
                      ...item,
                      chgAmount:values.chgAmount
                  }
                })
                const includes = this.loadData.some((i) => data?.map((j) => j.phoneCode1)?.includes(i.phoneCode1))
                if (!!includes) {
                  this.$message.error('存在相同串码')
                } else {
                  this.loadData = this.loadData.concat(data)
                }
                })
                .catch((error) => {
                  this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
                })
              }
            })
          },
        handleSubmit (e) {
            e.preventDefault()
            this.form1.validateFields((err, values) => {
              if (!err) {
                if(this.loadData.length == 0) {
                  this.$message.error('没有可调价的商品')
                  return false
                }
                const params = {
                  ...values,
                  orderDate: values.orderDate,
                  chgPriceListParams: this.loadData.map((item)=>{
                    return {
                      chgAmount:item.chgAmount,
                      commCost:item.commCost,
                      inventoryId:item.id
                    }
                }),
              }
                addChgPriceUsingPOST({},{data:params}).then((res) => {
                  this.$message.success('操作成功')
                  this.$router.push({ path: `/stock/changePriceRecord/${res.data.id}` })
                })
                .catch((error) => {
                  this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
                })
              }
            })
        },
        handleDel(record){
          const that = this
          that.$confirm({
            title: '删除',
            content: '你确定要删除这个商品吗？',
            okText: '确认',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
              that.loadData.splice( that.loadData.findIndex(item => item.id === record.id), 1)
              // this.loadData = this.loadData
            },
          })
        },
      }
    }
  </script>